package spindles.api.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.Validate;

public class FileUtil {

    public FileUtil() {        
    } 
    
    public static int getRecordsCount(File file){
    	final Integer[] counter = new Integer[]{0};
    	FileUtil.readFile(file, new Processor() {

			public void process(BufferedReader r) throws Exception {
				while(r.readLine() != null){
					counter[0] += 1; 
				}
				
			}
    		
    	});
    	
    	return counter[0];
    }
    
    public static void readFile(File file, Processor p){
        try {
			BufferedReader in = new BufferedReader(new FileReader(file));
			p.process(in);
			in.close();
		} catch (FileNotFoundException e) {
			throw new ApplicationException(e);
		} catch (IOException e) {
			throw new ApplicationException(e);
		} catch (Exception e) {
			throw new ApplicationException(e);
		}
    }
    
    public static void delete(String path){
    	try {
			if(validFile(path)){
				FileUtils.forceDelete(new File(path));
			}
		} catch (IOException e) {
			throw new ApplicationException(e);
		}
    }
    
    public static String stripExtension(String filename){
        int idx = filename.lastIndexOf(".");
        if(idx != -1){
            return filename.substring(0, idx);
        }
        return filename;        
    }
    
    private static boolean validFile(String path){
    	try {
			Validate.notEmpty(path);
		} catch (RuntimeException e) {
			return false;
		}
    	
    	File f = new File(path);
    	if(f.exists()){
    		return true;
    	}    	
    	
    	return false;
    }
    
    public static boolean validDir(String dir){    	
    	if(validFile(dir) && new File(dir).isDirectory()){
    		return true;
    	}    	
    	return false;
    }
    
    public static boolean validFilename(String filename){
    	if(validFile(filename) && new File(filename).isFile()){
    		return true;
    	}    	
    	return false;
    }
    
    public static String writeToDir(String path) throws UserException{
		if(Util.isEmpty(path)){
			throw new UserException(ErrorMessages.FILENAME_INVALID);
		}
		
		FileUtil.delete(path);
		
		File dir = new File(path);
		dir.mkdirs();
		
		return path;
	}

}
